package com.sankuai.inf.leaf.server.controller;


import com.sankuai.inf.leaf.segment.model.User;
import com.sankuai.inf.leaf.server.CommonException;
import com.sankuai.inf.leaf.server.config.LocalMvcConfiguration;
import com.sankuai.inf.leaf.server.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author final
 * @description
 * @date 2019-09-09 21:26
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @GetMapping("/")
    public String index(HttpSession session, Model model) {

        Object obj = session.getAttribute(LocalMvcConfiguration.SESSION_KEY);
        model.addAttribute("boy", obj);
        if (ObjectUtils.isEmpty(obj)) {
            return "/views/user/login.html";
        }
        return "/views/index.html";
    }

    @GetMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session, HttpServletResponse response) throws
        CommonException {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        boolean verify = loginService.login(user);
        if (verify) {
            session.setAttribute(LocalMvcConfiguration.SESSION_KEY, username);
            return "redirect:/views/index.html";
        } else {
            return "redirect:/views/user/login.html";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(LocalMvcConfiguration.SESSION_KEY);
        return "redirect:/views/user/login.html";
    }

}
